//
//  BLEViewModel.swift
//  BLE测试
//
//  Created by ls on 2018/1/26.
//  Copyright © 2018年 ls. All rights reserved.
//

import UIKit
import CoreBluetooth

protocol BLEViewModelDelegate {
    
    func BLEViewModelStatusHaveChange(status:CBCentralManagerState);
}

class BLEViewModel: NSObject {
    private let redWriteUUID  = CBUUID(string:"6E400002-B5A3-F393-E0A9-77656C6F6F70")
    private var writeCharacter:CBCharacteristic?
    
    private let serveUUID = CBUUID(string:"6E400001-B5A3-F393-E0A9-77656C6F6F70")
    private let batteryCharacterUUID = CBUUID(string:"FEA1")
    private let stepCharacterUUID = CBUUID(string:"FEA1")
    static let shareInstane = BLEViewModel.init()
    var delegate:BLEViewModelDelegate?
    

    var myPeripheral : CBPeripheral?
    private override init() {
        super.init()
        self.centerManger.delegate = self;

    }
    
    func writeBleWithValue(num:UInt8){
        print("writeValue:\(num)")
        let data = Data(bytes:[num])
        
        myPeripheral?.writeValue(data, for: writeCharacter!, type: .withoutResponse)
        myPeripheral?.readValue(for: writeCharacter!)
    }

    private func setupBLE(){
        let periphers = centerManger.retrieveConnectedPeripherals(withServices: [serveUUID])
        
        if(periphers.count>0)
        {
            for item:CBPeripheral in periphers {
                
                item.delegate=self
                myPeripheral = item
                centerManger.connect(item, options: nil)
                print(item)
            }
        }else{
            centerManger.scanForPeripherals(withServices: nil, options: nil)
        }
        
        
    }
    
    lazy var centerManger : CBCentralManager = {
        let manger = CBCentralManager()
        return manger
    }()

    

    
}
extension BLEViewModel:CBCentralManagerDelegate{
    
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
     
        switch central.state {
        case .poweredOn:
         setupBLE()
            break
//            centerManger.scanForPeripherals(withServices: nil, options: nil)
        default:
            break
        }
        
        delegate?.BLEViewModelStatusHaveChange(status: CBCentralManagerState(rawValue: central.state.rawValue)!)
        
        
    }
    
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {

        
        let ServeString = advertisementData["kCBAdvDataLocalName"] as! String
    
        if (ServeString.contains("WeLoop")) {
            self.myPeripheral = peripheral
            self.myPeripheral!.delegate = self
            centerManger.connect(peripheral, options: nil)
        }

    }
    func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
            print("didFailToConnect")
    }
    func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
        print("lost connect peripheral")
    }
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        print("didConnect")
        centerManger.stopScan()
        self.myPeripheral?.discoverServices(nil)
//        self.peripheral.delegate = self;
        
    }
    
    
}
extension BLEViewModel:CBPeripheralDelegate{
    
    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        
        for serve:CBService in peripheral.services! {
            
            peripheral.discoverCharacteristics(nil, for: serve)
        }
    }
    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
//        print(service.uuid.uuidString + "************")
        for character: CBCharacteristic in service.characteristics! {
          
            
//            print(character.uuid.uuidString,batteryCharacterUUID.uuidString)
            
            if(character.uuid.uuidString == batteryCharacterUUID.uuidString||character.uuid.uuidString==stepCharacterUUID.uuidString)
            {
                
               
                peripheral.readValue(for: character)
                peripheral.setNotifyValue(true, for: character)
            }
            if(character.uuid.uuidString==redWriteUUID.uuidString)
            {
                writeCharacter=character
            }
            
            
        }
        
    }
    
    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        
        let data = characteristic.value
        var numbersIterator = data!.makeIterator()
        while let num = numbersIterator.next() {
            print("\(characteristic.uuid.uuidString)-value:\(num)")
        }
        
 
        
        
    }
}
